package com.reebake.ideal.message.websocket.core;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.reebake.ideal.message.websocket.entity.WebsocketMessageTransferDTO;
import com.reebake.ideal.message.websocket.entity.WebsocketMessageTypeEnum;
import com.reebake.ideal.message.websocket.entity.WebsocketMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;

@Slf4j
public abstract class AbstractWebsocketMessageListener implements WebsocketMessageListener {
	@Autowired
	private SimpMessagingTemplate messagingTemplate;
	@Autowired
	private WebsocketServer websocketServer;

	@Override
    public void handleMessage(WebsocketMessageTransferDTO message) {
    	String destination = message.getDestination();
    	String receiver = message.getReceiver();
    	if(StrUtil.isBlank(destination)) {
    		log.warn("abort message because destination is null, message id is {}", message.getId());
    		return;
    	}
    	String content = message.getContent();
    	if(WebsocketMessageTypeEnum.TIP.equals(message.getType()) && StrUtil.isBlank(content)) {
    		log.warn("abort message because content is null, message id is {}", message.getId());
    		return;
    	}
    	
    	WebsocketMessageDTO websocketMessage = BeanUtil.copyProperties(message, WebsocketMessageDTO.class);
    	
    	if(StrUtil.isBlank(message.getReceiver())) {
    		messagingTemplate.convertAndSend(destination, websocketMessage);
    		websocketServer.sendMessageToAll(websocketMessage);
    	}else {
    		messagingTemplate.convertAndSendToUser(receiver, destination, websocketMessage);
    		websocketServer.sendMessage(receiver, websocketMessage);
    	}
    	
    }
}
